package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.activity.TeacherFansiListActivity.TeacherListAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.DelVideoRowid;
import com.ycsj.goldmedalnewconcept.bean.DelVideoRowidString;
import com.ycsj.goldmedalnewconcept.bean.TeacherManageResponse;
import com.ycsj.goldmedalnewconcept.bean.TeacherVideoInfo;
import com.ycsj.goldmedalnewconcept.bean.TeacherVideoResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.R;

//我的上传（个人视频）
public class MyUploadActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private RelativeLayout rl_upload;
	private TextView tv_bianji;
	private TextView tv_videonull;
	private TextView tv_allcheak;
	private TextView tv_del;
	private LinearLayout ll_checkbottom;
	private ListView lv_myself;

	private String CheckStatus = "0";
	private String account;
	private String role;
	private String allcheck ;
	private TeacherPrivateAdapter mAdapter;
	private List<TeacherVideoInfo> list; 
	private List<DelVideoRowid> dellist;
	private List<DelVideoRowidString> uploadinfo;
	private int p;
	private String json;  

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myupload);
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		list = new ArrayList<TeacherVideoInfo>();
		dellist = new ArrayList<DelVideoRowid>();
		uploadinfo = new ArrayList<DelVideoRowidString>();
		initView();
		setOnListener();
		initData();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		initData();
		super.onResume();
	}
	private void initView() {
		// TODO Auto-generated method stub
		iv_back = (ImageView) findViewById(R.id.iv_back);
		rl_upload = (RelativeLayout) findViewById(R.id.rl_upload);
		tv_bianji = (TextView) findViewById(R.id.tv_bianji);
		tv_allcheak = (TextView) findViewById(R.id.tv_allcheak);
		tv_videonull = (TextView) findViewById(R.id.tv_videonull);
		tv_del = (TextView) findViewById(R.id.tv_del);
		ll_checkbottom = (LinearLayout) findViewById(R.id.ll_checkbottom);
		lv_myself = (ListView) findViewById(R.id.lv_myself);

	}

	private void initData() {
		
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "25");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("teacherid", account);
		builder.add("vtype", "");
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=25&c=18271261779&role=2&teacherid=18271261779&vtype=0
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();

				String json = arg0.body().string();
				Log.e("test", json);
				TeacherVideoResponse fromJson = gson.fromJson(json,
						TeacherVideoResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								lv_myself.setVisibility(lv_myself.GONE);
								tv_videonull
										.setVisibility(tv_videonull.VISIBLE);
							}
						});
					} else if ("1".equals(fromJson.state)) {
						list = fromJson.list;
						
						mAdapter = new TeacherPrivateAdapter();

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								lv_myself.setVisibility(lv_myself.VISIBLE);
								lv_myself.setAdapter(mAdapter);
								tv_videonull
								.setVisibility(tv_videonull.GONE);
							}
						});
					}
				}
			}
		});
	}

	private void setOnListener() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		rl_upload.setOnClickListener(this);
		tv_bianji.setOnClickListener(this);
		tv_allcheak.setOnClickListener(this);
		tv_del.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_allcheak: // 全选
			
			allcheck = "1";
			if(mAdapter!=null){
				mAdapter.notifyDataSetChanged(); 
			}
			break;
		case R.id.tv_del: // 删除
			
			for (int i = 0; i < dellist.size(); i++) {
				DelVideoRowidString delvideorowid = new DelVideoRowidString();
				delvideorowid.rowid = list.get(dellist.get(i).row_id).row_id;
				uploadinfo.add(delvideorowid);
			}
			Gson gson=new Gson();
			 json = gson.toJson(uploadinfo);
			 Log.e("test", json);
			if(uploadinfo.size()==0){
				return;
			}
			deldialog();
			
			break;
		case R.id.tv_bianji: // 编辑
			if ("0".equals(CheckStatus)) {
				CheckStatus = "1";
				tv_bianji.setText("取消");
				ll_checkbottom.setVisibility(ll_checkbottom.VISIBLE);
				if(mAdapter!=null){
					mAdapter.notifyDataSetChanged(); 
				}
			} else if ("1".equals(CheckStatus)) {
				allcheck = "0";
				CheckStatus = "0";
				tv_bianji.setText("编辑");
				ll_checkbottom.setVisibility(ll_checkbottom.GONE);
				if(mAdapter!=null){
					mAdapter.notifyDataSetChanged(); 
				}
			}

			break;
		case R.id.rl_upload:
			Intent intent = new Intent(this, UploadVideoActivity.class);// 上传
			startActivity(intent);
			break;

		}
	}
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private String lESSON_NAME;

	public void setBasIn(BaseAnimatorSet bas_in) {
		this.bas_in = bas_in;
	}

	public void setBasOut(BaseAnimatorSet bas_out) {
		this.bas_out = bas_out;
	}
	private void deldialog() {
		// TODO Auto-generated method stub
		final NormalDialog dialog = new NormalDialog(this);
		dialog.content("确认删除已选的视频？").btnText("取消", "确认")//
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {
				dialog.dismiss();
			}
		});
		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				dialog.dismiss();
				OkHttpClient mOkHttpClient = new OkHttpClient();
				// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				FormEncodingBuilder builder = new FormEncodingBuilder();
				builder.add("type", "24");
				builder.add("c", account);
				builder.add("role", role);
				builder.add("jsonid", json);
				Request request = new Request.Builder()
						.url(Constant.SERVER_LOC + "ManageMsg").post(builder.build())
						.build();
				mOkHttpClient.newCall(request).enqueue(new Callback() {

// http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=24&c=18271261779&role=2&teacherid=18271261779&vtype=0
					@Override
					public void onFailure(Request arg0, IOException arg1) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
										.show();
							}
						});
					}

					@Override
					public void onResponse(Response arg0) throws IOException {
						// 解析Json数据，保存登录状态及身份信息

						Gson gson = new Gson();

						String json = arg0.body().string();
						Log.e("test", json);
						AttResponse fromJson = gson.fromJson(json,
								AttResponse.class);

						dellist = new ArrayList<DelVideoRowid>();
						uploadinfo = new ArrayList<DelVideoRowidString>();
						allcheck = "0";
						CheckStatus = "0";
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								tv_bianji.setText("编辑");
								ll_checkbottom.setVisibility(ll_checkbottom.GONE);
							}
						});
						
						
						if (fromJson != null) {
							if ("-1".equals(fromJson.state)) {
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(getBaseContext(), "删除失败，请重试", 0)
										.show();
									}
								});
							} else if ("1".equals(fromJson.state)) {
								
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(getBaseContext(), "删除成功！", 0)
										.show();
										initData();
									}
								});
							}
						}
					}
				});
				
			}
		});
	}

	class TeacherPrivateAdapter extends BaseAdapter {

		public int getCount() {

			return list.size();
		}

		public Object getItem(int position) {

			return null;
		}

		public long getItemId(int position) {

			return 0;
		}

		ViewHolder vh = null;

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(parent.getContext(),
						R.layout.item_teachervideo, null);
				vh = new ViewHolder();
				vh.cb_checkbox = (CheckBox) convertView
						.findViewById(R.id.cb_checkbox);
				vh.iv_videoimg = (ImageView) convertView
						.findViewById(R.id.iv_videoimg);
				vh.tv_videoname = (TextView) convertView
						.findViewById(R.id.tv_videoname);
				vh.tv_uploadtime = (TextView) convertView
						.findViewById(R.id.tv_uploadtime);
				vh.tv_playcount = (TextView) convertView
						.findViewById(R.id.tv_playcount);

				convertView.setTag(vh);
			} else {
				vh = (ViewHolder) convertView.getTag();
			}

			
			if("1".equals(CheckStatus)){
				vh.cb_checkbox.setVisibility(vh.cb_checkbox.VISIBLE);
				if("1".equals(allcheck)){
					vh.cb_checkbox.setChecked(true);
				}else if("0".equals(allcheck)){
					vh.cb_checkbox.setChecked(false);
				}
			}else{
				vh.cb_checkbox.setVisibility(vh.cb_checkbox.GONE);
			}
			
			Picasso.with(MyUploadActivity.this)
					.load(list.get(position).picture_url).into(vh.iv_videoimg);
			vh.tv_videoname.setText(list.get(position).title);
			vh.tv_uploadtime.setText(list.get(position).create_date + "上传");
			vh.tv_playcount.setText(list.get(position).play_times + "次播放");
			
			vh.cb_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					// TODO Auto-generated method stub
					p = position;
					Log.e("test", p+"pppp");
					if(!isChecked){
						Log.e("test", "true");
						for (int i = 0; i < dellist.size(); i++) {
							if(p==dellist.get(i).row_id){
								dellist.remove(i);
							}
						}
					}else{
						for (int i = 0; i < dellist.size(); i++) {
							if(p==dellist.get(i).row_id){
								dellist.remove(i);
							}
						}
						DelVideoRowid delvideorowid = new DelVideoRowid();
						delvideorowid.row_id = p;
						dellist.add(delvideorowid);
						Log.e("test", "false");
					}
				}
			});
			return convertView;
		}

		class ViewHolder {
			private CheckBox cb_checkbox;
			private ImageView iv_videoimg;
			private TextView tv_videoname;
			private TextView tv_uploadtime;
			private TextView tv_playcount;
		}
	}
}
